package com.v2future.sjt.collegecheckingattendance;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;
import com.mingle.widget.ShapeLoadingDialog;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.v2future.sjt.collegecheckingattendance.common.inject.ViewDefine;
import com.v2future.sjt.collegecheckingattendance.home.HomeActivity;
import com.v2future.sjt.collegecheckingattendance.home.adapter.OneLineTextAdapter;
import com.v2future.sjt.collegecheckingattendance.home.bean.LoginResultBean;
import com.v2future.sjt.collegecheckingattendance.home.bean.TermBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.DateUtil;
import com.v2future.sjt.collegecheckingattendance.utils.DensityUtil;
import com.v2future.sjt.collegecheckingattendance.utils.ImageUtil;
import com.v2future.sjt.collegecheckingattendance.utils.ToastUtil;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.DateTimePickDialogUtil;
import com.v2future.sjt.collegecheckingattendance.widget.crouton.Crouton;
import com.v2future.sjt.collegecheckingattendance.widget.crouton.Style;

import org.xutils.image.ImageOptions;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by sjt on 2016/1/2.
 * Activity基类
 */
public abstract class MainActivity extends FragmentActivity {

    /**
     * The my loading dialog.
     */
    private Dialog myLoadingDialog;
    private AnimationDrawable animationDrawable;

    public FragmentManager fragmentManager;

    /**
     * titlebar right loading icon animation
     */
    Animation rightIconAnimation = null;

    private ShapeLoadingDialog shapeLoadingDialog;

    public ArrayList<String> imageUrls = new ArrayList<>();
    public List<File> imageFiles = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        fragmentManager = getSupportFragmentManager();
        init();
        initView();
        //loading dialog need init first,
        // if not,
        // when it first display in the activity,
        // will stop a moment
        createLoadingDialog();
        initAfter();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    public MainApplication getBaseApplication(){
        return MainApplication.getInstance();
    }

    /**
     * set title text
     *
     * @param titleText 标题内容
     */
    public void setTitleText(String titleText) {
        if(isOver()) {
            return;
        }
        TextView titleTv = (TextView) findViewById(R.id.tv_title_text);
        if (null != titleTv) {
            titleTv.setText(titleText);
        }
    }

    /**
     * set title text
     *
     * @param strId 标题字符串id
     */
    public void setTitleText(int strId) {
        if(isOver()) {
            return;
        }
        TextView titleTv = (TextView) findViewById(R.id.tv_title_text);
        if (null != titleTv) {
            titleTv.setText(strId);
        }
    }

    /**
     * 获取当前标题
     * @return
     */
    public String getTitleText(){
        TextView titleTv = (TextView) findViewById(R.id.tv_title_text);
        if (null != titleTv) {
            return titleTv.getText().toString();
        }
        return "";
    }

    /**
     * init first
     */
    public abstract void init();

    /**
     * init view
     */
    public abstract void initView();

    /**
     * init after
     */
    public abstract void initAfter();

    /**
     * left image config
     *
     * @param imgId           icon image id
     * @param onClickListener the event of btn clicking
     */
    public void setLeftIcon(int imgId, View.OnClickListener onClickListener) {
        if(isOver()) {
            return;
        }
        ImageView leftIconIv = (ImageView) findViewById(R.id.iv_icon_left);
        LinearLayout leftLayout = (LinearLayout) findViewById(R.id.layout_left);
        if (null != leftIconIv && null != leftLayout) {
            leftIconIv.setImageResource(imgId);
            leftLayout.setOnClickListener(onClickListener);
            leftLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * init back
     * @param mListener if mListener is null, default finish this activity
     */
    public void initTitleBack(View.OnClickListener mListener){
        if (null != mListener) {
            setLeftIcon(R.mipmap.ic_back, mListener);
        }
        else {
            setLeftIcon(R.mipmap.ic_back, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    /**
     * right image config
     *
     * @param imgId           icon image id
     * @param onClickListener the event of btn clicking
     */
    public void setRightIcon(int imgId, View.OnClickListener onClickListener) {
        if(isOver()) {
            return;
        }
        ImageView rightIconIv = (ImageView) findViewById(R.id.iv_icon_right);
        LinearLayout rightLayout = (LinearLayout) findViewById(R.id.layout_right);
        if (null != rightIconIv) {
            rightIconIv.setImageResource(imgId);
            rightLayout.setOnClickListener(onClickListener);
            rightLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * right text
     * @param text
     * @param mListener
     */
    public void setRightText(String text, View.OnClickListener mListener){
        if(isOver()) {
            return;
        }
        TextView rightTv = (TextView) findViewById(R.id.tv_right);
        if (null != rightTv) {
            rightTv.setText(text);
            rightTv.setOnClickListener(mListener);
            rightTv.setVisibility(View.VISIBLE);
        }
    }

    public void hideRightText(){
        if(isOver()) {
            return;
        }
        TextView rightTv = (TextView) findViewById(R.id.tv_right);
        if (null != rightTv) {
            rightTv.setVisibility(View.GONE);
        }
    }

    /**
     * show right img loading
     */
    public void showTitleLoading() {
        if(isOver()) {
            return;
        }
        ImageView titleIconIv = (ImageView) findViewById(R.id.iv_icon_loading);
        if (null != titleIconIv) {
            titleIconIv.setImageResource(R.drawable.animation_loading);
            //set the image can be clicked
            titleIconIv.setClickable(false);
            animationDrawable = (AnimationDrawable) titleIconIv.getDrawable();
            animationDrawable.start();
            titleIconIv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * cancel right loading
     */
    public void cancelTitleLoading() {
        if(isOver()) {
            return;
        }
        ImageView titleIconIv = (ImageView) findViewById(R.id.iv_icon_loading);
        if (null != titleIconIv && titleIconIv.getVisibility() == View.VISIBLE) {
            titleIconIv.setClickable(true);
            animationDrawable.stop();
            titleIconIv.setVisibility(View.GONE);
        }
    }

    /**
     * right loading icon is showing ?
     *
     * @return
     */
    public boolean isTitleLoadingShowing() {
        ImageView rightIconIv = (ImageView) findViewById(R.id.iv_icon_right);
        return !(null == rightIconIv || animationDrawable == null) && animationDrawable.isRunning();
    }

    /**
     * show the dialog with one btn
     *
     * @param title
     * @param message
     * @param btnText
     * @param mListener
     */
    public void showOneBtnDialog(String title, String message, String btnText, View.OnClickListener mListener) {

        NiftyDialogBuilder builder = NiftyDialogBuilder.getInstance(this)
                .withTitle(title)
                .withDuration(500) //anim time
                .withEffect(Effectstype.Shake)  //animator
                .withMessage(message)
                .withButton1Text(btnText);
        if (null != mListener) {
            builder.setButton1Click(mListener);
        } else {
            builder.setButton1Click(dialogDismissListener);
        }
        if (!builder.isShowing()) {
            builder.show();
        }
    }

    /**
     * 显示一个简单的Dialog提示框
     * 只有一个按钮，并且没有时间处理
     * @param message 显示信息
     */
    public void showSimpleDialog(String message){
        showOneBtnDialog(getString(R.string.notice), message, getString(R.string.iknow), null);
    }

    /**
     * show the dialog with two btns
     *
     * @param title      title
     * @param message
     * @param btn1Text
     * @param m1Listener
     * @param btn2Text
     * @param m2Listener
     */
    public void showTwoBtnDialog(String title,
                                 String message,
                                 String btn1Text,
                                 View.OnClickListener m1Listener,
                                 String btn2Text,
                                 View.OnClickListener m2Listener) {
        NiftyDialogBuilder builder = NiftyDialogBuilder.getInstance(this)
                .withTitle(title)
                .withDuration(500)
                .withEffect(Effectstype.Shake)
                .withMessage(message)
                .withButton1Text(btn1Text)
                .withButton2Text(btn2Text);
        if (null != m1Listener) {
            builder.setButton1Click(m1Listener);
        } else {
            builder.setButton1Click(dialogDismissListener);
        }
        if (null != m2Listener) {
            builder.setButton2Click(m2Listener);
        } else {
            builder.setButton2Click(dialogDismissListener);
        }
        if (!builder.isShowing()) {
            builder.show();
        }
    }

    /**
     * dialog default listener
     */
    public View.OnClickListener dialogDismissListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HideDialog();
        }
    };

    /**
     * dismiss dialog
     */
    public void HideDialog() {
        if (NiftyDialogBuilder.getInstance(this).isShowing()) {
            NiftyDialogBuilder.getInstance(this).dismiss();
        }
    }

    /**
     * alert
     *
     * @param msg
     */
    public void tip(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            ToastUtil.showMessage(this, msg, Toast.LENGTH_SHORT);
        }
    }

    /**
     * alert
     * @param stringId
     */
    public void tip(int stringId){
        if (!TextUtils.isEmpty(getString(stringId))) {
            ToastUtil.showMessage(this, getString(stringId), Toast.LENGTH_SHORT);
        }
    }

    /**
     * top alert
     *
     * @param content
     */
    public void tipTop(String content) {
        Crouton crouton = Crouton.makeText(this, content, Style.ALERT);
        crouton.show();
    }

    /**
     * create loading dialog
     */
    public void createLoadingDialog() {
        shapeLoadingDialog = new ShapeLoadingDialog(this);
//        shapeLoadingDialog.setLoadingText("加载中...");
        DialogInterface.OnCancelListener mListener = new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                NetUtils.cancelRequest();
            }
        };
        shapeLoadingDialog.setDialogCancel(mListener);
    }

    /**
     * show loading dialog
     * 如果Dialgo被取消，相应的网络请求也会被取消
     */
    public void showLoadingDialog() {
        if (null == shapeLoadingDialog) {
            createLoadingDialog();
        }
//        animationDrawable.start();
        shapeLoadingDialog.show();
    }

    /**
     * hide loading dialog
     */
    public void cancelLoadingDialog() {
        if (null != shapeLoadingDialog) {
//            animationDrawable.stop();
            shapeLoadingDialog.dismiss();
        }
    }

    /**
     * go back the activity with data
     * instead of startActivityForResult
     * @param intent
     */
    public void gobackWithData(Intent intent){
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    /**
     *  go back home page
     */
    public void goHome(){
        Intent intent = new Intent(this, HomeActivity.class);
        gobackWithData(intent);
    }

    /**
     * 获取xUtils3图片默认配置，长宽120dp
     * @return
     */
    public ImageOptions getImageOptions(){
        return new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(this, 120), DensityUtil.dip2px(this, 120))
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setFailureDrawableId(R.mipmap.ic_img_load_error)
                .setLoadingDrawableId(R.mipmap.ic_album)
                .build();
    }

    public ImageOptions getImageOptions(int width, int height){
        return new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(this, width), DensityUtil.dip2px(this, height))
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setFailureDrawableId(R.mipmap.ic_img_load_error)
                .setLoadingDrawableId(R.mipmap.ic_album)
                .build();
    }

    public ImageOptions getCircleImageOptions(int width, int height){
        return new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(this, width), DensityUtil.dip2px(this, height))
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setCircular(true)
                .setFailureDrawableId(R.mipmap.ic_img_load_error)
                .setLoadingDrawableId(R.mipmap.ic_album)
                .build();
    }

    /**
     * 获取用户信息
     * @return
     */
    public LoginResultBean getUserInfo(){
        if (null != getBaseApplication().getCathe(Constants.CACHE_KEY_USER_INFO)) {
            return (LoginResultBean) getBaseApplication().getCathe(Constants.CACHE_KEY_USER_INFO);
        }
        else {
            return null;
        }
    }

    /**
     * 获取学期
     * @return
     */
    public TermBean getTerm(){
        if (null != getBaseApplication().getCathe(Constants.CACHE_KEY_TERM)) {
            return (TermBean) getBaseApplication().getCathe(Constants.CACHE_KEY_TERM);
        }
        else {
            return null;
        }
    }

    /**
     * 根据登录结果设置推送标签等
     * @param result
     */
    public void setPushTags(LoginResultBean result){
        //设置推送标签
        HashSet<String> tags = new HashSet<String>();
        tags.add(result.getData().getUserCode());
        int userIdentyType = 0;
        if (null != result && !TextUtils.isEmpty(result.getData().getSourceTypeId())) {
            userIdentyType = Integer.parseInt(result.getData().getSourceTypeId());
        }
        if (1 == userIdentyType) {
            tags.add(Constants.JPUSH_TAG_TEACHER);
        }
        else if (2 == userIdentyType) {
            tags.add(Constants.JPUSH_TAG_STUDENT);
        }
        JPushInterface.setAliasAndTags(this, null, tags);
    }

    /**
     * 返回头像资源id
     * @param headNumber
     * @return
     */
    public int getHeadIconId(int headNumber){
        int headId = 0;
        switch (headNumber) {
            case 1:
                headId = R.mipmap.ic_head_1;
                break;
            case 2:
                headId = R.mipmap.ic_head_2;
                break;
            case 3:
                headId = R.mipmap.ic_head_3;
                break;
            case 4:
                headId = R.mipmap.ic_head_4;
                break;
            case 5:
                headId = R.mipmap.ic_head_5;
                break;
            default:
                headId = R.mipmap.ic_head_1;
                break;
        }
        return headId;
    }

    /**
     * 给一个ImageView设置为默认头像
     * @param iv
     */
    public void setDefaultHead(ImageView iv){
        int headId = getHeadIconId(0);
        iv.setImageResource(headId);
    }

    /**
     * 列表样式dialog
     * @param dataList
     * @param tv
     */
    public void showListDialog(String[] dataList, final TextView tv){
        OneLineTextAdapter adapter = new OneLineTextAdapter(dataList, this);
        final DialogPlus dialogPlus = DialogPlus.newDialog(this)
                .setAdapter(adapter)
                .setCancelable(true)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (null != tv) {
                            tv.setText(String.valueOf(item));
                            dialog.dismiss();
                        }
                    }
                })
                .create();
        dialogPlus.show();
    }

    /**
     * 时间选择器dialog
     * @param timeTv
     */
    public void showTimeSelectDialog(TextView timeTv){
        DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(this, null);
        if (null != timeTv) dateTimePicKDialog.dateTimePicKDialog(timeTv);
    }

    /**
     * 压缩图片
     * @param filePath
     * @return
     */
    public File compressImageFile(String filePath, int id){
        String time = DateUtil.getCurrentDateTimeOnleyNumber();
        Bitmap bitmap = ImageUtil.file2Bitmap(filePath);
        byte[] b = ImageUtil.compressImage(bitmap, 300);
        bitmap.recycle();
        return ImageUtil.saveMyBitmap(b, "image"+time+"_"+id);
    }

    /**
     * 拼装地址字符串
     * @param cmd
     * @return
     */
    public String formatUrl(String cmd){
        return Constants.ServerUrl + cmd + Constants.DOT + Constants.ACTION;
    }

    /**
     * 拼接地址字符串，servlet的do
     * @param cmd
     * @return
     */
    public String formatUrlDo(String cmd){
        return Constants.ServerUrl + cmd + Constants.DOT + Constants.DO;
    }

    /**
     * url转码
     * @param str
     * @return
     */
    public String urlEncode(String str){
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析注解
     */
    public void autoInjectAllField() {
        try {
            Class<?> clazz = this.getClass();
            Field[] fields = clazz.getDeclaredFields();//获得Activity中声明的字段
            for (Field field : fields) {
                // 查看这个字段是否有我们自定义的注解类标志的
                if (field.isAnnotationPresent(ViewDefine.class)) {
                    ViewDefine inject = field.getAnnotation(ViewDefine.class);
                    int id = inject.value();
                    if (id > 0) {
                        field.setAccessible(true);
                        field.set(this, this.findViewById(id));//给我们要找的字段设置值
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输入法指定按键
     * 完成
     */
    public View.OnKeyListener onInputKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
				/*隐藏软键盘*/
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if(inputMethodManager.isActive()){
                    inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                inputActionEvent();
                return true;
            }
            return false;
        }
    };

    /**
     * 压缩图片
     */
    public void compressImages(){
        imageFiles.clear();
        if (null != imageUrls && imageUrls.size() > 0) {
            for (int i=0;i<imageUrls.size();i++) {
                imageFiles.add(compressImageFile(imageUrls.get(i).toString(), i));
            }
        }
    }

    /**
     * 压缩图片线程
     */
    public Thread imageCompressThread = new Thread(){
        @Override
        public void run() {
            super.run();
            compressImages();
            cancelLoadingDialog();
        }
    };

    /**
     * 更新用户信息
     */
    public void refreshUserInfo(){
            BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_USER_INFO));
            params.addQueryStringParameter("sourceTypeId",getUserInfo().getData().getSourceTypeId());
            NetUtils.doGetRequest(this, params, new NetTaskListener<LoginResultBean>() {

                @Override
                public void onSuccess(LoginResultBean result) {
                    if (null != result && !TextUtils.isEmpty(result.getData().getUserCode())) {
                        getBaseApplication().insertCathe(Constants.CACHE_KEY_USER_INFO, result);
                    }
                }

                @Override
                public void onError() {

                }

                @Override
                public void onInterError(LoginResultBean result) {

                }

                @Override
                public void onNetError(int responseCode, String responseMsg, String errorResult) {

                }

                @Override
                public void onCancelled() {

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onSuccessCache(LoginResultBean result) {

                }
            });
    }


    /**
     * 输入指定按键按下，重写方法
     */
    public void inputActionEvent(){}

    public String getClassSimpleName(Class c){
        return c.getSimpleName();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shapeLoadingDialog = null;
    }

    /**
     * is the activity finished ?
     *
     * @return
     */
    public boolean isOver() {
        boolean isDes = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            isDes = isDestroyed();
        }
        return (isFinishing() || isDes);
    }
}
